package com.laiketui.admin.store.controller.store.util;

import java.math.BigDecimal;

public class AmountConverter {

    private static final String[] CN_UPPER_NUMBER = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    private static final String[] CN_UNIT = {"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万"};
    private static final String[] CN_DECIMAL_UNIT = {"角", "分"};

    public static String toChineseUpperCase(BigDecimal amount) {
        if (amount == null) {
            return "";
        }

        BigDecimal integerPart = amount.setScale(0, BigDecimal.ROUND_DOWN);
        BigDecimal decimalPart = amount.subtract(integerPart);

        // 处理整数部分
        String integerStr = integerPart.toString();
        StringBuilder result = new StringBuilder();

        boolean leadingZero = true;
        for (int i = 0; i < integerStr.length(); i++) {
            int digit = Character.digit(integerStr.charAt(i), 10);
            int unitIndex = integerStr.length() - i - 1;

            if (digit == 0) {
                if (!leadingZero && result.charAt(result.length() - 1) != '零') {
                    result.append("零");
                }
                leadingZero = true;
            } else {
                leadingZero = false;
                result.append(CN_UPPER_NUMBER[digit]);
                result.append(unitIndex < CN_UNIT.length ? CN_UNIT[unitIndex] : "");
            }
        }

        // 添加“元”
        if (result.length() > 0) {
            result.append("元");
        }

        // 处理小数部分
        if (decimalPart.compareTo(BigDecimal.ZERO) > 0) {
            String decimalStr = decimalPart.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).toString();
            if(decimalStr.length() < 2){
                decimalStr='0'+decimalStr;
            }
            for (int i = 0; i < decimalStr.length(); i++) {
                int digit = Character.digit(decimalStr.charAt(i), 10);
                result.append(CN_UPPER_NUMBER[digit]);
                result.append(CN_DECIMAL_UNIT[i]);
            }
        } else {
            result.append("整");
        }

        return result.toString();
    }

    public static void main(String[] args) {
        BigDecimal amount = new BigDecimal("1234560.00");
        System.out.println(toChineseUpperCase(amount));  // 输出: 壹佰贰拾叁万肆仟伍佰陆拾柒元捌角玖分
    }
}